#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from typing import List, Dict
from .base import FilterRule

class TrailingSymbolChangeFilter(FilterRule):
    """语句尾部装饰符变动过滤规则 - 过滤末尾添加的标点符号等风格微调"""

    def __init__(self, trailing_symbols: List[str] = None):
        if trailing_symbols is None:
            trailing_symbols = [
                # 中文标点
                '。', '，', '；', '：', '！', '？', '“', '”', '‘', '’',
                # 英文标点
                '.', ',', ';', ':', '!', '?', '"', "'",
                # 其他装饰符
                ' ', '\t', '\n', '、', '…', '~', '-', '_'
            ]
        self.trailing_symbols = trailing_symbols

    def should_filter(self, add_content: str, remove_content: str, hunk_changes: List[Dict]) -> bool:
        """判断是否为尾部装饰符变动"""
        if add_content == remove_content:
            return False
        return self._is_trailing_symbol_change(add_content, remove_content)

    def _is_trailing_symbol_change(self, add_content: str, remove_content: str) -> bool:
        """检查是否为尾部装饰符变动"""
        add_core = self._remove_trailing_symbols(add_content)
        remove_core = self._remove_trailing_symbols(remove_content)

        # 内容相等且非空，尾部符号可变
        if add_core == remove_core and add_core:
            add_trailing = add_content[len(add_core):]
            remove_trailing = remove_content[len(remove_core):]
            return self._contains_only_trailing_symbols(add_trailing) and \
                   self._contains_only_trailing_symbols(remove_trailing)
        return False

    def _remove_trailing_symbols(self, content: str) -> str:
        """去掉尾部装饰符"""
        if not content:
            return ""
        i = len(content) - 1
        while i >= 0 and content[i] in self.trailing_symbols:
            i -= 1
        return content[:i + 1]

    def _contains_only_trailing_symbols(self, content: str) -> bool:
        """检查内容是否只包含尾部装饰符"""
        if not content:
            return True
        return all(char in self.trailing_symbols for char in content)

    def get_filter_reason(self) -> str:
        return "trailing_symbol_change"
